package cn.tedu.spring.security.service;

import cn.tedu.spring.security.pojo.param.LoginParam;
import cn.tedu.spring.security.security.AdminDetails;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService{

    @Autowired
    AuthenticationManager authenticationManager;

    @Value("${csmall.jwt.secret-key}")
    private String secretKey;

    @Override
    public String login(LoginParam loginParam) {
        log.debug("开始处理【自定义登录】的业务");
        Authentication authentication = new UsernamePasswordAuthenticationToken(
                loginParam.getUsername(),loginParam.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authentication);
        log.debug("验证登录成功!结果为:{}",authenticate);

        Object principal = authenticate.getPrincipal();
        AdminDetails adminDetails = (AdminDetails) principal;
        Collection<GrantedAuthority> authorities = adminDetails.getAuthorities();

        //生成jwt
        Map<String,Object> claims = new HashMap<>();
        claims.put("id",adminDetails.getId());
        claims.put("username",adminDetails.getUsername());
        claims.put("authoritiesJsonString", JSON.toJSONString(authorities));

        String jwt = Jwts.builder()
                .setHeaderParam("alg","HS256")
                .setHeaderParam("typ","JWT")
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis()+100000000))
                .signWith(SignatureAlgorithm.HS256,secretKey)
                .compact();
        return jwt;
    }
}
